package com.hantanger.weblog.freemarker;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import com.google.gson.Gson;

public class Utils {

	public static Date long2Date(long time) {
		return new Date(time);
	}

	public static String obj2Json(Object obj) {
		Gson gson = new Gson();
		return gson.toJson(obj);
	}

	/**
	 * 生成gravatar头像
	 * 
	 * @param email
	 * @return
	 */
	public static String genAvatar(String email) {
		if (email == null) {
			email = "";
		}
		return "http://www.gravatar.com/avatar/" + MD5(email);
	}

	/**
	 * 生成md5加密码
	 * 
	 * @param s
	 * @return
	 */
	public static String MD5(String s) {
		if (StringUtils.isBlank(s)) {
			return null;
		}
		try {
			byte[] btInput = s.getBytes();
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			mdInst.update(btInput);
			byte[] md = mdInst.digest();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < md.length; i++) {
				int val = ((int) md[i]) & 0xff;
				if (val < 16)
					sb.append("0");
				sb.append(Integer.toHexString(val));
			}
			return sb.toString();
		} catch (Exception e) {
			return null;
		}
	}

	public static String formatTime(long time) {
		long now = System.currentTimeMillis();
		long delta = now - time;
		if (delta > DateUtils.MILLIS_PER_DAY) {
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return format.format(new Date(time));
		}
		if (delta > DateUtils.MILLIS_PER_HOUR) {
			return (delta / DateUtils.MILLIS_PER_HOUR) + "小时前";
		}
		if (delta > 30 * DateUtils.MILLIS_PER_MINUTE) {
			return "半小时前";
		}
		if (delta > 15 * DateUtils.MILLIS_PER_MINUTE) {
			return "一刻钟前";
		}
		if (delta > 10 * DateUtils.MILLIS_PER_MINUTE) {
			return "10分钟前";
		}
		if (delta > 5 * DateUtils.MILLIS_PER_MINUTE) {
			return "5分钟前";
		}
		return "1分钟前";
	};

	public static void main(String[] args) {
		// System.out.println(obj2Json(Ar));
	}

}
